<script setup>
import { appStore } from '@/sotre/modules/app';
import { onShow } from '@dcloudio/uni-app';
import { dayjs } from 'wot-design-uni';
import { getEnterpriseList } from '@/utils/request';

const { userInfo, power, products } = toRefs(appStore());
const $post = inject('$post');
const $get = inject('$get');
const $put = inject('$put');

const show = ref(false);
const date = ref(3);
const picker = ref();
const code = ref(uni.getStorageSync('myCode'));
const base64 = ref('');
const integral = ref(0);
const req = reactive({
    type: 2,
    enterpriseId: uni.getStorageSync('enterpriseId'),
    startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().add(date.value, 'days').format('YYYY-MM-DD HH:mm:ss'),
});

const getCode = () => {
    req.endTime = dayjs().add(date.value, 'days').format('YYYY-MM-DD HH:mm:ss');
    $post('/platform/platformInviteCode/addInviteCode', req).then(res => {
        code.value = res.data;
        uni.setStorageSync('myCode', code.value);
        getQrcode();
    });
};

const getQrcode = () => {
    const path = `pages/index/index`;
    $post(`/platform/wx/getQRCode?page_url=${path}&scene=invite=${code.value}`).then(res => {
        base64.value = res.data.qr_code;
    });
};

if (!code.value) {
    getCode();
} else {
    getQrcode();
}

onShow(() => {
    $post('/platform/users/getUserInfo').then(async res => {
        if (res.code === 200) {
            userInfo.value = res.data.platformUsers;
            // 获取积分
            const { data: r } = await $get(
                `/platform/integral/get/${userInfo.value.lastEnterpriseId}`
            );
            integral.value = r;
        }
    });
});

const phone = computed(() => {
    if (userInfo.value.phone) {
        return userInfo.value.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    }
    return '--';
});

const isVip = computed(() => {
    if (
        userInfo.value.currEnterpriseByCache.appUserPower &&
        userInfo.value.currEnterpriseByCache.appUserPower.length > 0 &&
        userInfo.value.currEnterpriseByCache.appUserPower.some(
            item => new Date(item.expiredTime) > new Date()
        )
    ) {
        return true;
    }
    return false;
});

const link = computed(() => {
    return `${import.meta.env.VITE_DOMAIN}?invite=${code.value}`;
});

const handleShare = () => {
    show.value = true;
};

const openPicker = () => {
    picker.value.open();
};

const goVip = () => {
    uni.navigateTo({
        url: '/pages/my/components/human',
    });
};

const shareQrcode = () => {
    // #ifdef H5
    try {
        // 将base64转换为blob
        const byteCharacters = atob(base64.value);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: 'image/png' });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `qrcode_${Date.now()}.png`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        uni.showToast({ title: '保存成功', icon: 'success' });
    } catch (error) {
        console.log('保存失败：', error);
        uni.showToast({ title: '保存失败', icon: 'none' });
    }
    // #endif
    // #ifdef MP-WEIXIN
    try {
        const fs = uni.getFileSystemManager();
        const tempFilePath = `${uni.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;

        // 将base64转换为二进制数据
        const buffer = uni.base64ToArrayBuffer(base64.value);

        fs.writeFile({
            filePath: tempFilePath,
            data: buffer,
            encoding: 'binary',
            success: () => {
                uni.showShareImageMenu({
                    path: tempFilePath,
                });
            },
            fail: err => {
                console.log('写入文件失败：', err);
                uni.showToast({ title: '分享失败', icon: 'none' });
            },
        });
    } catch (error) {
        console.log('分享失败：', error);
        uni.showToast({ title: '分享失败', icon: 'none' });
    }
    // #endif
};

const copyLink = () => {
    uni.setClipboardData({
        data: link.value,
    });
    uni.showToast({ title: '复制成功', icon: 'success' });
};

function joinTeam() {
    uni.showModal({
        title: '加入团队',
        content: '',
        placeholderText: '请输入邀请码',
        modelValue: '',
        editable: true,
        success: res => {
            if (res.confirm) {
                console.log(res.content);
                if (!res.content) return;
                $put('/platform/users/invite', { code: res.content }).then(res => {
                    if (res.code == 200) {
                        userInfo.value = res.data.user.platformUsers;
                        power.value = res.data.permissions.map(item => item.split(':')[2]);
                        uni.setStorageSync(
                            'X-Enterprise-ID',
                            res.data.user.platformUsers.lastEnterpriseId
                        );
                        uni.showToast({ title: '加入团队成功', icon: 'success' });
                        getEnterpriseList();
                        showTeam.value = true;
                        uni.showToast({ title: '已自动切换该团队', icon: 'success' });
                    }
                });
            }
        },
    });
}

function codeFun() {
    uni.showModal({
        title: '兑换码',
        content: '',
        placeholderText: '请输入兑换码',
        modelValue: '',
        editable: true,
        success: async res => {
            if (res.confirm) {
                if (!res.content) return;
                const r = await $post(`/platform/redeemCode/redeem/${res.content}`);
                if (r.code == 200) {
                    uni.showToast({
                        title: '兑换成功',
                        icon: 'success',
                    });
                    // 获取最新自己的产品数据
                    $get('/platform/platformEnterprise/products').then(s => {
                        products.value = s.data;
                    });
                }
            }
        },
    });
}
</script>

<template>
    <div class="index">
        <u-navbar title="个人中心" left-icon="" bg-color="transparent"></u-navbar>
        <div class="bg">
            <div class="user">
                <wd-img
                    :src="userInfo?.avatar || '/static/image/fox.png'"
                    width="60"
                    height="60"
                    round
                >
                    <template #error>
                        <image
                            src="/static/image/fox.png"
                            style="width: 50px"
                            mode="widthFix"
                        ></image>
                    </template>
                </wd-img>
                <div class="info">
                    <span class="name">{{ userInfo.name }}</span>
                    <div class="row">
                        <div class="enrerprise">
                            <wd-img
                                src="/static/image/bluev.png"
                                width="14"
                                mode="widthFix"
                            ></wd-img>
                            <span>{{ userInfo.currEnterpriseByCache.name }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bottom">
                <image src="/static/my/bg_vip.png" mode="widthFix" class="bg_img"></image>
                <wd-img
                    src="/static/my/icon_vip.png"
                    width="40"
                    height="28"
                    mode="widthFix"
                ></wd-img>
                <span style="z-index: 9">会员可享超多特权，去升级。</span>
                <wd-button type="warning" size="small" @click="goVip">
                    {{ isVip ? '去续费' : '去升级' }}
                </wd-button>
            </div>
        </div>
        <div class="grid">
            <wd-cell-group border>
                <wd-cell title="账户钻石" is-link size="large" to="/pages/my/components/integral">
                    <template #icon>
                        <wd-img src="/static/my/walte.png" width="24" mode="widthFix"></wd-img>
                    </template>
                    <span class="integral">{{ integral }}</span>
                </wd-cell>
                <!-- <wd-cell title="会员套餐" is-link size="large" to="/pages/my/components/vip">
                    <template #icon>
                        <wd-img src="/static/my/vip.png" width="24" mode="widthFix"></wd-img>
                    </template>
                </wd-cell> -->
                <wd-cell title="会员套餐" is-link size="large" to="/pages/my/components/human">
                    <template #icon>
                        <wd-img src="/static/my/vip.png" width="24" mode="widthFix"></wd-img>
                    </template>
                </wd-cell>
                <wd-cell title="兑换码" is-link size="large" @click="codeFun">
                    <template #icon>
                        <wd-img src="/static/my/dhm.png" width="24" mode="widthFix"></wd-img>
                    </template>
                </wd-cell>
                <wd-cell title="分享团队链接" clickable size="large" @click="handleShare">
                    <template #icon>
                        <wd-img src="/static/my/link.png" width="24" mode="widthFix"></wd-img>
                    </template>
                    <template #default>
                        <wd-icon name="chevron-right" size="22px" color="#c7c7c7"></wd-icon>
                    </template>
                </wd-cell>
                <wd-cell title="加入团队" is-link size="large" @click="joinTeam">
                    <template #icon>
                        <wd-img src="/static/my/team.png" width="24" mode="widthFix"></wd-img>
                    </template>
                </wd-cell>
                <wd-cell title="订单管理" is-link size="large" to="/pages/my/components/order">
                    <template #icon>
                        <wd-img src="/static/my/order.png" width="24" mode="widthFix"></wd-img>
                    </template>
                </wd-cell>
                <wd-cell title="设置" is-link size="large" to="/pages/my/components/set">
                    <template #icon>
                        <wd-img src="/static/my/set.png" width="24" mode="widthFix"></wd-img>
                    </template>
                </wd-cell>
            </wd-cell-group>
        </div>
        <wd-popup v-model="show" custom-style="border-radius:32rpx;" closable>
            <div class="share">
                <div class="title">分享链接</div>
                <div class="column">
                    <span class="label">数字邀请码</span>
                    <div class="code">{{ code }}</div>
                </div>
                <div class="column">
                    <span class="label">链接二维码邀请</span>
                    <div class="row">
                        <div class="code">
                            <div class="link">{{ link }}</div>
                            <div class="right" @click="openPicker">
                                <span>{{ date }}天</span>
                                <wd-icon name="chevron-down" size="18px" color="#c7c7c7"></wd-icon>
                            </div>
                        </div>
                        <u-button type="warning" @click="copyLink">复制链接</u-button>
                    </div>
                </div>
                <div class="qr">
                    <wd-img
                        :src="`data:image/png;base64,${base64}`"
                        width="100px"
                        mode="widthFix"
                        show-menu-by-longpress
                    ></wd-img>
                    <span style="font-size: 12px">长按保存图片</span>
                    <u-button type="warning" @click="shareQrcode">分享二维码</u-button>
                </div>
            </div>
        </wd-popup>
        <wd-picker
            :columns="[
                { label: '3天', value: 3 },
                { label: '5天', value: 5 },
                { label: '7天', value: 7 },
            ]"
            v-model="date"
            ref="picker"
            @confirm="getCode"
        />
    </div>
</template>

<style scoped lang="scss">
.index {
    :deep(.wd-picker) {
        position: fixed;
        top: -10000px;
        z-index: 999999;
    }
    .share {
        border-radius: 32rpx;
        background: #fff;
        border-radius: 15px;
        width: 80vw;
        display: flex;
        flex-direction: column;
        gap: 15px;
        padding-bottom: 20px;
        .title {
            padding: 15px 0;
            font-weight: bold;
            text-align: center;
            font-size: 18px;
        }
        .column {
            padding: 0 15px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            .code {
                padding: 7px 12px;
                border: 1px solid #ebebeb;
                border-radius: 5px;
                color: #2b2b2b;
                flex: 1;
                display: flex;
                align-items: center;
                .link {
                    flex: 1;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    max-width: 150px;
                }
                .right {
                    display: flex;
                    align-items: center;
                    gap: 5px;
                    color: #f9712e;
                    margin-left: auto;
                }
            }
            .label {
                font-weight: bold;
            }
            .row {
                display: flex;
                align-items: center;
                gap: 10px;
            }
        }
        .qr {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            gap: 12px;
            margin-top: 10px;
            :deep(.wd-img) {
                padding: 5px;
                border: 1px solid #ebebeb;
                border-radius: 5px;
            }
        }
        :deep(.u-button) {
            width: fit-content;
        }
    }
    .bg {
        background-image: linear-gradient(-20deg, #e9defa 0%, #fbfcdb 100%);
        width: 100%;
        height: 300px;
        position: relative;
        .bottom {
            position: absolute;
            bottom: 10px;
            left: 0;
            right: 0;
            height: 70px;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            width: calc(90% - 30px);
            left: 5%;
            display: flex;
            align-items: center;
            padding: 0 15px;
            color: #f9712e;
            border-radius: 15px;
            line-height: 28px;
            font-size: 14px;
            .bg_img {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }
        }
    }
    .user {
        border-radius: 10px;
        margin: 10px 15px 12px 15px;
        display: flex;
        align-items: center;
        gap: 12px;
        position: absolute;
        top: 100px;
        left: 0;
        .enrerprise {
            // position: absolute;
            bottom: -30px;
            left: 0;
            padding: 3px 10px;
            border-radius: 10px;
            background: #e5e7f1;
            font-size: 11px;
            align-items: center;
            background: #e5e7f1;
            display: flex;
        }

        .info {
            .name {
                font-size: 18px;
                font-weight: 600;
            }
            .cor {
                padding: 3px 10px;
                border-radius: 10px;
                background: #e5e7f1;
                font-size: 11px;
                color: #2b2b2b;
                width: fit-content;
            }
            .row {
                display: flex;
                align-items: center;
                gap: 10px;
                margin-top: 5px;
            }
        }
        .set {
            margin-left: auto;
        }
    }
    .grid {
        position: relative;
        padding: 10px 15px;
        border-radius: 15px 15px 0 0;
        top: -15px;
        background: #fff;
        height: calc(100vh - 400px);
        .integral {
            font-weight: bold;
        }
        :deep(.wd-cell__title) {
            padding-left: 10px;
        }
    }
}
</style>
